import Koa from "koa";
import errDir from "./err.dir.json";

type TError = "3001";
type TStatus = 404 | 204;
export default () => async (ctx: Koa.Context, next: () => Promise<any>) => {
  await next().then(() => {

    if (ctx.status === 200) {
      ctx.body = {
        code: "200", // 200 表示成功，可以根据实际情况定义其他的状态码
        msg: 'success',
        success: true,
        data: ctx.body,
      };
    } else {
      ctx.body = {
        success: false,
        code: ctx.status,
        msg: errDir.status[ctx.status as TStatus],
        data: null,
      };
    }
    if (ctx.status === 204) {
      ctx.body = 204;
    }
  }).catch((err: {
    code: TError;
    msg?: string;
  }) => {
    ctx.body = {
      data: null,
      success: false,
      code: err.code,
      msg: err.msg || errDir.code[err.code],
    };
  });

};
